package com.feiyu.file.controller;

import com.alibaba.fastjson.JSON;
import com.feiyu.file.service.FileService;
import com.feiyu.resource.entity.Resource;
import org.apache.tomcat.util.json.JSONParser;
import org.springblade.core.tool.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author tang ming
 * @since 2021/12/6 19:35
 */
@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    private FileService fileService;

    @Value("${server.port}")
    private String port;

    /**
     * 实现资源上传更新
     * @param file 上传的文件
     * @param resource 文件存到数据所需的信息
     * */
    @PostMapping("/res/upload")
    public R<String> uploadResource(MultipartFile file,@RequestParam("resource") String resource){

        return R.data(fileService.uploadResource(file, JSON.parseObject(resource,Resource.class)));
    }

    @PostMapping("/img/upload")
    public R uploadImage(MultipartFile file){
        return R.data(fileService.uploadImage(file));
    }

    @GetMapping("/download/{id}")
    public void download(@PathVariable("id") long id, HttpServletResponse response){
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("UTF-8");
        fileService.download(id, response);
    }
    @GetMapping("/url")
    public R<String> getUrl() throws UnknownHostException {
        InetAddress localHost = InetAddress.getLocalHost();
        String address = localHost.getHostAddress();
        return R.data("http://"+address+":"+port+"/file/download/");
    }

    @PostMapping("/delete")
    public R delete(long id,String type){
        return R.status(fileService.delete(id, type));
    }

    @GetMapping("/server")
    public R<String> getServer() throws UnknownHostException {
        return R.data(InetAddress.getLocalHost().getHostAddress());
    }
}
